﻿using LayuiMvc.DataEntity.IdentityEntity;
using LayuiMvc.DataModel.Identity;
using LayuiMvc.Logic.Identity;
using LayuiMvcUtil.Exception;
using LayuiMvcUtil.Result;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace LayuiMvc.WebUI.Controllers
{
    public class AccountController : Controller
    {
        #region 初始化管理器
        private IdentityUserManager UserManager
        {
            get { return HttpContext.GetOwinContext().GetUserManager<IdentityUserManager>(); }
        }

        private IdentitySignInManager SignInManager
        {
            get { return HttpContext.GetOwinContext().Get<IdentitySignInManager>(); }
        }
        /// <summary>
        /// 授权管理器
        /// </summary>
        private IAuthenticationManager AuthenicationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }

        #endregion

        #region 账户管理==加载用户信息
        
        /// <summary>
        /// 加载用户信息
        /// 注意：分部视图不允许异步加载
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadUserMsg()
        {
            UserMsgModel userMsgModel = new UserMsgModel();
            userMsgModel.IsLogin = HttpContext.User.Identity.IsAuthenticated;

            if (userMsgModel.IsLogin)
            {
                int userId = HttpContext.User.Identity.GetUserId<int>();
                IdentityUserEntity userEntity = UserManager.FindById(userId);

                userMsgModel.UserId = userEntity.Id;
                userMsgModel.NickName = userEntity.NickName;
                userMsgModel.Sex = userEntity.Sex;
                userMsgModel.HeadImgUrl = userEntity.HeadImgUrl;
                userMsgModel.UserIdentity = userEntity.UserIdentity;
                userMsgModel.IsApprove = userEntity.IsApprove;
                userMsgModel.ApproveMsg = userEntity.ApproveMsg;
            }
            return PartialView("_Header", userMsgModel);
        }
        #endregion

        #region 账户管理==用户注册
        /// <summary>
        /// 用户注册视图跳转
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="registerModel">要注册的用户模型类</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Register(UserRegisterModel registerModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            try
            {
                await UserManager.UserRegisterAsync(registerModel);

            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }
            return Json(rtnResult);
        }
        #endregion

        #region 账户管理==用户登录

        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginModel">用户登录模型类</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Login(UserLoginModel loginModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            try
            {
                await SignInManager.UserLoginAsync(loginModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }
            return Json(rtnResult);
        }
        #endregion

        #region 账户管理==退出登录
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult SignOut()
        {
            AuthenicationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return RedirectToAction("Login");
        }
        #endregion

        #region 用户管理==用户信息设置
        
        /// <summary>
        /// 用户信息设置页面跳转
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> UserSet()
        {
            int userId = HttpContext.User.Identity.GetUserId<int>();
            UserMsgModel userMsgModel = await UserManager.UpdateUserMsgInit(userId);
            return View(userMsgModel);
        }
        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="userMsgModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UserSet(UserMsgModel userMsgModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            try
            {
                userMsgModel.UserId = HttpContext.User.Identity.GetUserId<int>();
                await UserManager.UpdateUserMsgAsync(userMsgModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }

            return Json(rtnResult);
        }
        #endregion

        #region 账户管理==用户头像修改
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> UpdateHeadImg()
        {
            int userId = HttpContext.User.Identity.GetUserId<int>();
            UserMsgModel userMsgModel = await UserManager.UpdateUserMsgInit(userId);
            return View(userMsgModel);
        }
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> UpdateUserHeadImg()
        {
            int userId = HttpContext.User.Identity.GetUserId<int>();
            DataResult<string> rtnResult = new DataResult<string>();
            HttpPostedFileBase file = Request.Files[0];
            if (file!=null&&!string.IsNullOrEmpty(file.FileName))
            {
                var saveFileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + file.FileName;

                file.SaveAs(Path.Combine(Server.MapPath("~/UploadFile/HeadImg"), saveFileName));

                await UserManager.UpdateUserHeadImgAsync(userId, $"/UploadFile/HeadImg/{saveFileName}");

                rtnResult.data = $"/UploadFile/HeadImg/{saveFileName}";
            }
            return Json(rtnResult);
        }
        #endregion

        #region 账户管理==修改密码

        /// <summary>
        /// 修改账户密码
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> UpdatePassword()
        {
            int userId = HttpContext.User.Identity.GetUserId<int>();
            UserMsgModel userMsgModel = await UserManager.UpdateUserMsgInit(userId);
            return View(userMsgModel);
        }
        [HttpPost]
        public async Task<ActionResult> UpdatePassword(UpdatePasswordModel updatePasswordModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();
            int userId = HttpContext.User.Identity.GetUserId<int>();
            try
            {
                updatePasswordModel.UserId = userId;
                await UserManager.UpdateUserPasswordAsync(updatePasswordModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }
            return Json(rtnResult);
        }
        #endregion
    }
}